/**
 * Project Name:api-webhook
 * File Name:ChsiService.java
 * Package Name:com.example.service.webhook.business.chsi.service
 * Date:2016年7月26日下午4:07:19
 * Copyright (c) 2016, yuandong@51dojo.com All Rights Reserved.
 */

package com.example.service.webhook.business.jingdong.service;

import com.example.service.webhook.business.jingdong.api.JingdongClient;
import com.example.service.webhook.business.jingdong.billitem.JdBillTask;
import com.example.service.webhook.business.jingdong.dto.*;
import com.example.service.webhook.business.jingdong.entity.*;
import com.example.service.webhook.business.jingdong.repository.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * JingdongService <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2016年7月26日 下午4:07:19 <br/>
 *
 * @author yuandong
 * @see
 * @since JDK 1.6
 */
@Service
public class JingdongService {

    private static final Logger LOGGER = LoggerFactory.getLogger(JingdongService.class);

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private JingdongClient jingdongClient;
    @Autowired
    private JdUserInfoRepository jdUserInfoRepository;
    @Autowired
    private JdDeliverAddressRepository jdDeliverAddressRepository;
    @Autowired
    private JdWealthRepository jdWealthRepository;
    @Autowired
    private JdTradeInfoRepository jdTradeInfoRepository;
    @Autowired
    private JdProductInfoRepository jdProductInfoRepository;

    @Autowired
    private JdBindCardRepository jdBindCardRepository;

    @Autowired
    private JdBtBillRepository jdBtBillRepository;

    @Autowired
    private JdJinTiaoBillRepository jdJinTiaoBillRepository;

    @Autowired
    private JdJinTiaoBillPlanRepository jdJinTiaoBillPlanRepository;

    /**
     * fetchBill:处理京东回调 <br/>
     * 在收到魔蝎的邮箱账单回调时执行<br/>
     * 基本信息<br/>
     * 收货地址<br/>
     * 收货地址<br/>
     *
     * @param task
     * @author yuandong
     * @since JDK 1.6
     */
    public void fetchBill(final JdBillTask task) {

        // 这里交给线程池处理，防止下面的业务处理时间太长，导致超时。
        // 超时会导致魔蝎数据进行重试，会收到重复的回调请求

        taskExecutor.execute(new Runnable() {
                                 @Override
                                 public void run() {
                                  saveAllData(task);

                                 }
                             }

        );

    }

    /*private void saveUserInfo(JdBillTask task) {
        try {
            JdUserInfo userinfo = jingdongClient.getUserInfo(task.getTaskId());
            if (userinfo != null) {
                JdUserInfoEntity jingdongUserInfoEntity = new JdUserInfoEntity();
                BeanUtils.copyProperties(userinfo, jingdongUserInfoEntity);
                jingdongUserInfoEntity.setUserId(task.getUserId());
                JdUserInfoEntity isExistEntity = jdUserInfoRepository.getUserInfo(task.getUserId(),
                        task.getMappingId());
                if (isExistEntity != null) {
                    jingdongUserInfoEntity.setCreateTime(isExistEntity.getCreateTime());
                    jingdongUserInfoEntity.setId(isExistEntity.getId());
                    jdUserInfoRepository.updateUserInfo(jingdongUserInfoEntity);
                } else {
                    jdUserInfoRepository.saveUserInfo(jingdongUserInfoEntity);
                }
            }
        } catch (Exception e) {
            LOGGER.error("处理京东客户基本信息出现异常", e);
        }

    }*/

   /* private void saveDeliverAddress(JdBillTask task) {
        try {
            jdDeliverAddressRepository.deleteDeliverAddress(task.getUserId(), task.getMappingId());
            loadDeliverAddressByCallApi(task.getTaskId(), task.getUserId());
        } catch (Exception e) {
            LOGGER.error("saveDeliverAddress error", e);
        }
    }

    private void loadDeliverAddressByCallApi(String taskId, String userId) throws Exception {
        List<JdDeliverAddress> deliverAddressList = jingdongClient.getDeliverAddress(taskId);
        if (deliverAddressList != null && !deliverAddressList.isEmpty()) {
            for (JdDeliverAddress deliverAddress : deliverAddressList) {
                JdDeliverAddressEntity basicEntity = new JdDeliverAddressEntity();
                BeanUtils.copyProperties(deliverAddress, basicEntity);
                basicEntity.setUserId(userId);
                jdDeliverAddressRepository.saveDeliverAddress(basicEntity);
            }
        }
    }*/

    /*private void saveWealth(JdBillTask task) {
        try {
            JdWealth jdWealth = jingdongClient.getWealth(task.getTaskId());
            if (jdWealth != null) {
                JdWealthEntity jdWealthEntity = new JdWealthEntity();
                BeanUtils.copyProperties(jdWealth, jdWealthEntity);
                jdWealthEntity.setUserId(task.getUserId());
                JdWealthEntity isExistEntity = jdWealthRepository.getWealth(task.getUserId(), task.getMappingId());
                if (isExistEntity != null) {
                    jdWealthEntity.setCreateTime(isExistEntity.getCreateTime());
                    jdWealthEntity.setId(isExistEntity.getId());
                    jdWealthRepository.updateWealth(jdWealthEntity);
                } else {
                    jdWealthRepository.saveWealth(jdWealthEntity);
                }
            }
        } catch (Exception e) {
            LOGGER.error("处理京东资产状况出现异常", e);
        }

    }*/

    /*private void saveTradeDetails(JdBillTask task) {
        int page = 1;
        int pageSize = 200;
        try {

            do {
                JdTradeDetailsRes tradeDetailsRes = jingdongClient.getTradeDetailsRes(task.getTaskId(), page, pageSize);
                if (tradeDetailsRes != null && tradeDetailsRes.getSize() > 0) {
                    pageSize = tradeDetailsRes.getSize();
                    List<JdTradeDetails> tradeDetailsList = tradeDetailsRes.getTradedetails();
                    for (JdTradeDetails tradeDetails : tradeDetailsList) {
                        JdTradeDetailsEntity tradeDetailEntity = new JdTradeDetailsEntity();
                        BeanUtils.copyProperties(tradeDetails, tradeDetailEntity);
                        tradeDetailEntity.setUserId(task.getUserId());

                        // 保存消费记录
                        JdTradeDetailsEntity isExist = jdTradeInfoRepository.getTradeDetailEntity(task.getUserId(),
                                task.getMappingId(), tradeDetails.getTradeId());
                        if (isExist == null) {
                            jdTradeInfoRepository.saveTradeDetail(tradeDetailEntity);
                        } else {
                            tradeDetailEntity.setId(isExist.getId());
                            tradeDetailEntity.setCreateTime(isExist.getCreateTime());
                            jdTradeInfoRepository.updateTradeDetail(tradeDetailEntity);
                        }

                        // 保存商品信息
                        List<JdProductInfo> subOrders = tradeDetails.getProducts();
                        if (subOrders != null && !subOrders.isEmpty()) {
                            jdProductInfoRepository.deleteProductInfo(task.getUserId(), tradeDetails.getMappingId(),
                                    tradeDetails.getTradeId());
                            for (JdProductInfo jdProductInfo : subOrders) {
                                JdProductInfoEntity jdProductInfoEntity = new JdProductInfoEntity();
                                BeanUtils.copyProperties(jdProductInfo, jdProductInfoEntity);
                                jdProductInfoEntity.setUserId(task.getUserId());
                                jdProductInfoRepository.saveProductInfo(jdProductInfoEntity);
                            }
                        }

                    }
                } else {
                    pageSize = 0;
                }
                page++;
            } while (pageSize == 200);
        } catch (Exception e) {
            LOGGER.error("saveTradeDetails error", e);
        }
    }*/

    /**
     * 保存所有数据
     *
     * @param task
     */
    private void saveAllData(JdBillTask task) {

        try {
            JdUserAllData userAllData = jingdongClient.getUserAllData(task.getTaskId());

            //保存用户信息
            JdUserInfo userinfo = userAllData.getJdUserInfo();
            if (userinfo != null) {
                JdUserInfoEntity jingdongUserInfoEntity = new JdUserInfoEntity();
                BeanUtils.copyProperties(userinfo, jingdongUserInfoEntity);
                jingdongUserInfoEntity.setUserId(task.getUserId());
                JdUserInfoEntity isExistEntity = jdUserInfoRepository.getUserInfo(task.getUserId(),
                        task.getMappingId());
                if (isExistEntity != null) {
                    jingdongUserInfoEntity.setCreateTime(isExistEntity.getCreateTime());
                    jingdongUserInfoEntity.setId(isExistEntity.getId());
                    jdUserInfoRepository.updateUserInfo(jingdongUserInfoEntity);
                } else {
                    jdUserInfoRepository.saveUserInfo(jingdongUserInfoEntity);
                }
            }
            //快递地址
            try {
                jdDeliverAddressRepository.deleteDeliverAddress(task.getUserId(), task.getMappingId());
                List<JdDeliverAddress> deliverAddressList = userAllData.getJdDeliverAddressList();
                if (deliverAddressList != null && !deliverAddressList.isEmpty()) {
                    for (JdDeliverAddress deliverAddress : deliverAddressList) {
                        JdDeliverAddressEntity basicEntity = new JdDeliverAddressEntity();
                        BeanUtils.copyProperties(deliverAddress, basicEntity);
                        basicEntity.setUserId(task.getUserId());
                        jdDeliverAddressRepository.saveDeliverAddress(basicEntity);
                    }
                }
            } catch (Exception e) {
                LOGGER.error("saveDeliverAddress error", e);
            }

            //财富
            JdWealth jdWealth = userAllData.getJdWealth();
            if (jdWealth != null) {
                JdWealthEntity jdWealthEntity = new JdWealthEntity();
                BeanUtils.copyProperties(jdWealth, jdWealthEntity);
                jdWealthEntity.setUserId(task.getUserId());
                JdWealthEntity isExistEntity = jdWealthRepository.getWealth(task.getUserId(), task.getMappingId());
                if (isExistEntity != null) {
                    jdWealthEntity.setCreateTime(isExistEntity.getCreateTime());
                    jdWealthEntity.setId(isExistEntity.getId());
                    jdWealthRepository.updateWealth(jdWealthEntity);
                } else {
                    jdWealthRepository.saveWealth(jdWealthEntity);
                }
            }

            //交易信息
            JdTradeDetailsRes tradeDetailsRes = userAllData.getJdTradeDetailsRes();
            if (tradeDetailsRes != null && tradeDetailsRes.getSize() > 0) {
                List<JdTradeDetails> tradeDetailsList = tradeDetailsRes.getTradedetails();
                for (JdTradeDetails tradeDetails : tradeDetailsList) {
                    JdTradeDetailsEntity tradeDetailEntity = new JdTradeDetailsEntity();
                    BeanUtils.copyProperties(tradeDetails, tradeDetailEntity);
                    tradeDetailEntity.setUserId(task.getUserId());

                    // 保存消费记录
                    JdTradeDetailsEntity isExist = jdTradeInfoRepository.getTradeDetailEntity(task.getUserId(),
                            task.getMappingId(), tradeDetails.getTradeId());
                    if (isExist == null) {
                        jdTradeInfoRepository.saveTradeDetail(tradeDetailEntity);
                    } else {
                        tradeDetailEntity.setId(isExist.getId());
                        tradeDetailEntity.setCreateTime(isExist.getCreateTime());
                        jdTradeInfoRepository.updateTradeDetail(tradeDetailEntity);
                    }

                    // 保存商品信息
                    List<JdProductInfo> subOrders = tradeDetails.getProducts();
                    if (subOrders != null && !subOrders.isEmpty()) {
                        jdProductInfoRepository.deleteProductInfo(task.getUserId(), tradeDetails.getMappingId(),
                                tradeDetails.getTradeId());
                        for (JdProductInfo jdProductInfo : subOrders) {
                            JdProductInfoEntity jdProductInfoEntity = new JdProductInfoEntity();
                            BeanUtils.copyProperties(jdProductInfo, jdProductInfoEntity);
                            jdProductInfoEntity.setUserId(task.getUserId());
                            jdProductInfoRepository.saveProductInfo(jdProductInfoEntity);
                        }
                    }

                }
            }

            //保存绑定卡信息
            List<JdBindCardInfo> cardInfos = userAllData.getJdBindCardInfoList();
            if (null != cardInfos) {
                for (JdBindCardInfo cardInfo : cardInfos) {
                    JdBindCardEntity cardEntity = new JdBindCardEntity();
                    BeanUtils.copyProperties(cardInfo, cardEntity);
                    cardEntity.setUserId(task.getUserId());
                    JdBindCardEntity isExistBindCard = jdBindCardRepository.getBindCard(task.getUserId(), cardInfo.getMappingId());
                    if (null != isExistBindCard) {
                        cardEntity.setCreateTime(isExistBindCard.getCreateTime());
                        cardEntity.setId(isExistBindCard.getId());
                        jdBindCardRepository.updateBindCard(cardEntity);
                    } else {
                        jdBindCardRepository.saveBindCard(cardEntity);
                    }
                }
            }


            //保存京东白条
            List<JdBtBill> btBillList = userAllData.getJdBtBillList();
            if (null != btBillList) {
                for (JdBtBill btBill : btBillList) {
                    JdBtBillEntity btBillEntity = new JdBtBillEntity();
                    BeanUtils.copyProperties(btBill, btBillEntity);
                    btBillEntity.setUserId(task.getUserId());
                    JdBtBillEntity isBtBillEntity = jdBtBillRepository.getBtBill(task.getUserId(), btBill.getMappingId());
                    if (null != isBtBillEntity) {
                        btBillEntity.setCreateTime(isBtBillEntity.getCreateTime());
                        btBillEntity.setId(isBtBillEntity.getId());
                        jdBtBillRepository.updateBtBill(btBillEntity);
                    } else {
                        jdBtBillRepository.saveBtBill(btBillEntity);
                    }

                }
            }

            //保存京东金条借款记录
            JdJtBill jtBill = userAllData.getJdJtBill();
            if (null != jtBill) {
                List<JdJinTiaoBill> jinTiaoBills = jtBill.getJdJinTiaoBills();
                for (JdJinTiaoBill jinTiaoBill : jinTiaoBills) {
                    JdJinTiaoBillEntity jinTiaoBillEntity = new JdJinTiaoBillEntity();
                    BeanUtils.copyProperties(jinTiaoBill, jinTiaoBillEntity);
                    jinTiaoBillEntity.setUserId(task.getUserId());
                    JdJinTiaoBillEntity isExistJtb = jdJinTiaoBillRepository.getJinTiaoBillEntity(task.getUserId(), jinTiaoBill.getMappingId(), jinTiaoBill.getLoanId());
                    if (null != isExistJtb) {
                        jinTiaoBillEntity.setCreateTime(isExistJtb.getCreateTime());
                        jinTiaoBillEntity.setId(isExistJtb.getId());
                        jdJinTiaoBillRepository.updateJinTiaoBill(jinTiaoBillEntity);
                    } else {
                        jdJinTiaoBillRepository.saveJinTiaoBill(jinTiaoBillEntity);
                    }

                    //保存京东金条还款计划信息
                    List<JdJinTiaoBillPlan> jinTiaoBillPlanList = jinTiaoBill.getPlans();
                    for (JdJinTiaoBillPlan jinTiaoBillPlan : jinTiaoBillPlanList) {
                        JdJinTiaoBillPlanEntity jinTiaoBillPlanEntity = new JdJinTiaoBillPlanEntity();
                        BeanUtils.copyProperties(jinTiaoBillPlan, jinTiaoBillPlanEntity);
                        jinTiaoBillPlanEntity.setUserId(task.getUserId());
                        JdJinTiaoBillPlanEntity isExistJtbp = jdJinTiaoBillPlanRepository.getJinTiaoBillPlan(task.getUserId(), jinTiaoBillPlan.getMappingId(), jinTiaoBillPlan.getPlanId());
                        if (null != isExistJtbp) {
                            jinTiaoBillEntity.setCreateTime(isExistJtbp.getCreateTime());
                            jinTiaoBillEntity.setId(isExistJtbp.getId());
                            jdJinTiaoBillPlanRepository.update(jinTiaoBillPlanEntity);
                        } else {
                            jdJinTiaoBillPlanRepository.saveJinTiaoBillPlan(jinTiaoBillPlanEntity);
                        }

                    }
                }


            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


}
